<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="handDownload"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card class="box-card" style="margintop: 15px">
        <el-table
          border
          :data="userList"
          :default-sort="{ prop: 'mobile', order: 'ascending' }"
        >
          <el-table-column label="序号" type="56'index" width="50" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffPhoto"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" sortable label="手机号" />
          <el-table-column prop="workNumber" sortable label="工号" />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatter"
            label="聘用形式"
          />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" sortable label="转正时间">
            <template v-slot="scope">
              {{ scope.row.correctionTime | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="asignRoleFn(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delFn(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 新增角色对话框 -->
        <el-dialog
          title="新增成员"
          :visible.sync="showDialog"
          width="50%"
          @close="closeFn"
        >
          <!-- 子组件 -->
          <empDialog
            ref="empDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @close="closeFn"
            @uploadlist="uploadlist"
          />
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoledialog"
          width="50%"
        >
          <assign-role v-if="showRoledialog" :user-id="parentId" @close="showRoledialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入组件
// import PageTools from '@/components/PageTools'
import { getUserList, delUser } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'
import assignRole from './components/assignRole'
export default {
  name: 'Employees',
  components: {
    empDialog,
    assignRole
  },
  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      // 分页数据
      query: {
        page: 1,
        size: 10
      },
      total: 0,
      userList: [],
      showDialog: false,
      showRoledialog: false, // 控制角色分配弹框
      parentId: null
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    asignRoleFn(id) {
      this.showRoledialog = true
      this.parentId = id
    },
    // 格式化表格数据,导出功能,将英文翻译成中文,导出到表格里
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 拿到所有英文名
      const Eheader = Object.keys(rows[0])
      // 遍历修改,item是英文
      const header = Eheader.map(item => {
        // 返回中文标题  map[item],返回中文值
        return map[item]
      })
      // 数据修改,数据需要[[]]格式
      const data = rows.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },

    // excel导出功能
    async handDownload() {
      const res = await getUserList(this.query)
      const dataObj = this.transData(res.data.rows)

      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: dataObj.header, // 表头 必填
          data: dataObj.data, // 具体数据 必填
          filename: 'excel-list', // 非必填,文件名称
          autoWidth: true, // 非必填,是否自适应宽度
          bookType: 'xlsx' // 非必填,导出文件形式
        })
      })
    },
    closeFn() {
      this.$refs.empDialog.resetFrom()
      this.showDialog = false
    },

    // 子组件在父组件执行,关闭弹窗和刷新功能
    uploadlist() {
      this.showDialog = false
      this.getUserList()
    },
    // 枚举渲染到下拉框
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      return obj ? obj.value : '未知'
    },
    // 渲染列表
    async getUserList() {
      const res = await getUserList(this.query)
      this.userList = res.data.rows
      this.total = res.data.total
    },
    // 改变分页
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getUserList()
    },
    // 改变当前页
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getUserList()
    },
    // 删除用户4步  1.询问框 2.给用户处理成功或者取消提示消息 3.成功调用接口 4.刷新页面
    async delFn(id) {
      // 1询问框
      const confirmRes = await this.$confirm(
        '此操作将永久删除该成员, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes === 'cancel') return this.$message('已取消删除')

      const res = await delUser(id)
      if (this.userList.length === 1) {
        this.query.page--
        if (this.page <= 0) {
          this.query.page = 1
        }
      }
      this.$message.success(res.message)
      this.getUserList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>

